//登录，注册，忘记密码相关的api都放在这里
const express = require('express');
const bodyParser = require('body-parser');
const router = express.Router();
const db = require('../database/db');
const jwt = require('jsonwebtoken');
// const config = require('../config');
const GlobalUtil = require('../Util/GlobalUtil');
const nodemailer = require('nodemailer');
const fs = require('fs');

//生成Token的函数
function generateToken(payload) {
    return jwt.sign(payload, process.env.SECRETKEY, {
        expiresIn: '7d', 
        algorithm: 'HS256',
    });
}

router.use(bodyParser.text());  //请求为纯文本格式时自动解析为字符串
router.use(bodyParser.json());  //自动反序列化为json对象,挂载到req.body上

//请求登录
router.post('/RequestLogin', (req, res) => {
    const email = req.body.email;
    const password = req.body.password;
    // db.query(`SELECT * FROM user WHERE email = '${email}' AND password = '${password}`, (err, result) => {
    //上面的写法会导致sql注入问题，所以使用下面“参数化查询”写法
    const sql  = 'SELECT * FROM user WHERE email = ? AND password = ?';
    db.query(sql, [email, password], async (err, result) => {
        if (err) {
            //处理数据库查询错误
            res.status(500).send("Database error");
            return;
        }
        if (result.length > 0) {
            const user_id = result[0].user_id;
            const payload = {
                user_id: String(user_id),
                email: email,
            }
            const token = generateToken(payload);
            res.send({msg: '登陆成功', token: token});
            // 更新账号信息
            try {
                const LoginTime = GlobalUtil.getDateTime();
                const sql = "UPDATE user SET last_login_time = ? WHERE user_id = ?";
                const result = await GlobalUtil.asyncQuery(sql, [LoginTime, user_id]);
            } catch (error) {
                console.error(error);
            }
        } else {
            //用户不存在或者密码错误
            res.status(401).send("用户不存在或者密码错误");
        }
    })
})

//请求验证码
router.post('/RequestGetCode', (req, res) => {
    const email = req.body.email;
    const code = GlobalUtil.generateRandomCode();
    const is_used = 0;
    const created_at = GlobalUtil.getDateTime();
    const expires_at = GlobalUtil.getDateTime(300);
    const ip_address = req.socket.remoteAddress;

    const transporter = nodemailer.createTransport({
        host: 'smtp.qq.com', //QQ邮箱的SMTP服务器地址
        port: 465, //SSL，端口号465或587
        secure: true, //使用SSL加密
        auth: {
            user: process.env.SMTP_USER, //QQ邮箱
            pass: process.env.SMTP_PASSWORD //QQ邮箱授权码
        }
    });
    //邮件内容
    const mailOptions = {
        from: 'mail_4824@qq.com', //发件人地址
        to: email, //收件人地址
        subject: '奶龙向大佬投喂一封验证码',
        text: `你的验证码是：${code}，验证码将在5分钟内过期，请及时使用。`, //纯文本内容
        html: 
        `<p>奶了个龙验证码为：</p>
        <br>
        <h1>${code}</h1>
        <br>
        <p>验证码将在5分钟内过期，请及时使用。</p>`
    }
    
    //发送邮件
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.log(error);
            res.status(500).send("验证码发送失败");
            return;
        } else {
            console.log('验证码发送成功：' + info.messageId);
            res.send({msg: "验证码已发送\n请登录邮箱查看\n未收到可检查垃圾箱"});
            //把邮件存入数据库中
            sql = 'INSERT INTO verification_codes (email, code, is_used, created_at, expires_at, ip_address) VALUES (?, ?, ?, ?, ?, ?)';
            db.query(sql, [email, code, is_used, created_at, expires_at, ip_address], (err, result) => {
                if (err) {
                    res.status(500).send("Database error");
                    console.error('Database error', err);
                    //考虑将错误信息写入本地的日志文件
                    return;
                }
            })
        }
    })
}) 

//请求注册
router.post('/RequestRegister', (req, res) => {
    const RegisterData = {
        email: req.body.email,
        password: req.body.password,
        AuthCode: req.body.AuthCode
    }
    //判断邮箱有没有注册过
    const sql = 'SELECT * FROM user WHERE email = ?';
    db.query(sql, [RegisterData.email], (err, result) => {
        if (err) {
            res.status(500).send("Database error");
            return;
        }
        if (result.length > 0) {
            res.status(400).send("邮箱已被注册!");
            return;
        } else {
            //判断验证码是否正确
            const CurrentTime = GlobalUtil.getDateTime();
            const sql = 'SELECT * FROM verification_codes WHERE email = ? AND code = ? AND is_used = 0 AND expires_at > ?';
            db.query(sql, [RegisterData.email, RegisterData.AuthCode, CurrentTime], (err, result) => {
                if (err) {
                    res.status(500).send("Database error");
                    return;
                }
                if (result.length > 0) {
                    // 验证码验证正确，修改此验证码为已使用状态
                    const updateSql = 'UPDATE verification_codes SET is_used = 1 WHERE email = ? AND code = ?';
                    db.query(updateSql, [RegisterData.email, RegisterData.AuthCode], (err, updateResult) => {
                        if (err) {
                            res.status(500).send("Database error while updating verification code");
                            return;
                        }
                    });

                    // 注册新用户
                    const UserData = {
                        email: RegisterData.email,
                        password: RegisterData.password,
                        register_time: CurrentTime,
                        last_login_time: null,
                    }
                    const sql = 'INSERT INTO user (email, password, register_time, last_login_time) VALUES (?, ?, ?, ?)';
                    db.query(sql, [UserData.email, UserData.password, UserData.register_time, UserData.last_login_time], (err, result) => {
                        if (err) {
                            res.status(500).send("注册失败！");
                            console.log("失败",err)
                            return;
                        } else {
                            //往item表中初始化数据
                            const UserData = {
                                user_id: result.insertId,
                                nickname: "用户: " + result.insertId,
                                avatar_url: "/Avatar/nwwn.png"
                            }
                            const sql_userdata = 'INSERT INTO userdata (user_id, nickname, avatar_url) VALUES (?, ?, ?)';
                            db.query(sql_userdata, [UserData.user_id, UserData.nickname, UserData.avatar_url], (err, result) => {
                                if (err) {
                                    res.status(500).send("数据库错误");
                                    return;
                                }
                                res.send("注册成功！\n请返回登录！");
                            })
                        }
                    })
                } else {
                    res.status(400).send("验证码错误或已过期");
                    return;
                }
            })
        }
    })
})

//忘记密码后请求修改密码
router.post('/RequestForget', (req, res) => {
    const ForgetData = {
        email: req.body.email,
        password: req.body.password,
        AuthCode: req.body.AuthCode
    }
    // 判断邮箱有没有注册过
    const sql = 'SELECT * FROM user WHERE email = ?';
    db.query(sql, [ForgetData.email], (err, result) => {
        if (err) {
            res.status(500).send("Database error");
            return;
        }   //查询结果为0也是没有错误，所以即使没有错误也要对查询结果进行长度判断
        if (result.length === 0) {
            res.status(400).send("邮箱未注册！");
            return;
        } else {
            //数据库中查询到了邮箱，开始验证码校验
            authCodeVerify(ForgetData.email, ForgetData.AuthCode, res, () => {
                //验证通过，修改密码
                const sql = 'UPDATE user SET password = ? WHERE email = ?';
                db.query(sql, [ForgetData.password, ForgetData.email], (err, result) => {
                    if (err) {
                        res.status(500).send("修改密码失败！");
                        return;
                    } else {
                        res.send("修改密码成功！\n请返回登录！");
                    }
                })
            })
        }
    })
})

//校验验证码, func:验证通过后执行的函数
function authCodeVerify(email, authCode, res, func = {}) {
    const CurrentTime = GlobalUtil.getDateTime();
    const sql = 'SELECT * FROM verification_codes WHERE email = ? AND code = ? AND is_used = 0 AND expires_at > ?'
    db.query(sql, [email, authCode, CurrentTime], (err, result) => {
        if (err) {
            res.status(500).send("Database error");
            return;
        }
        if (result.length === 0) {
            res.status(400).send("验证码错误或已过期");
            return;
        }
        if (result.length > 0) {
            //查找到匹配的验证码, 将该验证码标记为已使用
            const updateSql = 'UPDATE verification_codes SET is_used = 1 WHERE email = ? AND code = ?';
            db.query(updateSql, [email, authCode], (err, updateResult) => {
                if (err) {
                    res.status(500).send("Database error while updating verification code");
                    return;
                }
            });
            //执行验证成功之后的操作
            func();
        }
    })
}

module.exports = router;